

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://i.loli.net/2021/11/21/KLIcp3NhoymnFP2.jpg">
  <link rel="icon" href="https://i.loli.net/2021/11/21/KLIcp3NhoymnFP2.jpg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="逝者如斯夫，不舍昼夜。">
  <meta name="author" content="余龙">
  <meta name="keywords" content="">
  <meta name="description" content="原型每个函数对象当中都有一个属性叫prototype。 该属性指向的是一个对象，这个对象就是原型对象。 如果函数作为普通函数调用，则原型对象没有任何作用。 如果作为构造函数调用，那么通过该构造函数所创建的对象中都会有一个隐含的属性指向函数的原型对象（prototype）。  12&#x2F;&#x2F;实例的隐式原型指向类（构造函数）的显示原型实例.__proto__ &#x3D;&#x3D;&#x3D; 类.prototype   也就是说该类">
<meta property="og:type" content="article">
<meta property="og:title" content="什么是原型和原型链？">
<meta property="og:url" content="http://gis-yu.gitee.io/gis-yu/2022/01/04/%E4%BB%80%E4%B9%88%E6%98%AF%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%8E%9F%E5%9E%8B%E9%93%BE%EF%BC%9F/index.html">
<meta property="og:site_name" content="YL&#39;Blog">
<meta property="og:description" content="原型每个函数对象当中都有一个属性叫prototype。 该属性指向的是一个对象，这个对象就是原型对象。 如果函数作为普通函数调用，则原型对象没有任何作用。 如果作为构造函数调用，那么通过该构造函数所创建的对象中都会有一个隐含的属性指向函数的原型对象（prototype）。  12&#x2F;&#x2F;实例的隐式原型指向类（构造函数）的显示原型实例.__proto__ &#x3D;&#x3D;&#x3D; 类.prototype   也就是说该类">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.loli.net/2022/01/04/YiEhw1XFDTx98Um.png">
<meta property="og:image" content="https://s2.loli.net/2022/01/04/M1ryHKhQuC3Xl98.png">
<meta property="article:published_time" content="2022-01-04T12:47:40.000Z">
<meta property="article:modified_time" content="2022-01-04T12:51:43.476Z">
<meta property="article:author" content="余龙">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://s2.loli.net/2022/01/04/YiEhw1XFDTx98Um.png">
  
  <title>什么是原型和原型链？ - YL&#39;Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/gis-yu/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/atom-one-dark.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/gis-yu/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"gis-yu.gitee.io","root":"/gis-yu/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/gis-yu/local-search.xml"};
  </script>
  <script  src="/gis-yu/js/utils.js" ></script>
  <script  src="/gis-yu/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 60vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/gis-yu/">
      <strong>YL&#39;Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/gis-yu/">
                <i class="iconfont icon-home-fill"></i>
                主页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/gis-yu/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/gis-yu/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/gis-yu/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/gis-yu/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://i.loli.net/2021/11/22/PJswpxfBROKm2M7.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="什么是原型和原型链？">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-01-04 20:47" pubdate>
        2022年1月4日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.2k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      4 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">什么是原型和原型链？</h1>
            
            <div class="markdown-body">
              <h2 id="原型"><a href="#原型" class="headerlink" title="原型"></a>原型</h2><p>每个<strong>函数对象</strong>当中都有一个属性叫prototype。</p>
<p>该属性指向的是一个对象，这个对象就是原型对象。</p>
<p>如果函数作为普通函数调用，则原型对象没有任何作用。</p>
<p>如果作为构造函数调用，那么通过该构造函数所创建的对象中都会有一个隐含的属性指向函数的原型对象（prototype）。</p>
<p><img src="https://s2.loli.net/2022/01/04/YiEhw1XFDTx98Um.png" srcset="/gis-yu/img/loading.gif" lazyload alt="image-20220104154956589"></p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//实例的隐式原型指向类（构造函数）的显示原型</span><br>实例.__proto__ === 类.prototype<br></code></pre></div></td></tr></table></figure>

<p><img src="https://s2.loli.net/2022/01/04/M1ryHKhQuC3Xl98.png" srcset="/gis-yu/img/loading.gif" lazyload alt="image-20220104155406611"></p>
<p>也就是说该类的所有实例中都会有一个隐含的属性执行构造函数的prototype。</p>
<h3 id="原型对象，就相当于一个公共区域可以被所有的该类实例访问。"><a href="#原型对象，就相当于一个公共区域可以被所有的该类实例访问。" class="headerlink" title="原型对象，就相当于一个公共区域可以被所有的该类实例访问。"></a>原型对象，就相当于一个公共区域可以被所有的该类实例访问。</h3><p>可以将一些实例共有的属性或方法存储在原型对象当中，这样只需要设置一次即可让所有的对象都访问到这些属性和方法。</p>
<p>向原型中添加一个name属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//向原型中添加一个name属性。</span><br>Myclass.prototype.name = <span class="hljs-string">&quot;向原型添加name&quot;</span><br><br><span class="hljs-built_in">console</span>.log(mc.name);<br><br><span class="hljs-comment">//结果：向原型添加name</span><br></code></pre></div></td></tr></table></figure>

<h3 id="原型链"><a href="#原型链" class="headerlink" title="原型链"></a>原型链</h3><p>当我们访问一个对象中的属性时，JS会先在<strong>对象本身中</strong>寻找，如果对象中没有该属性，则会到<strong>对象的原型中</strong>（__proto__）寻找。如果还是没找到，则到<strong>原型的原型</strong>中寻找。以此类推…，直到找到Object的原型，如果依然没有，则返回undefined。这个搜寻的过程称为<strong>原型链</strong>。</p>
<p><strong>Object的prototype是所有对象的原型，它的原型是null。</strong></p>
<h2 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h2><p>定义一个类时，如果属性和方法是对象独有的，就直接在构造函数中设置。</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> 类名(<span class="hljs-params"></span>)</span>&#123;<br>    <span class="hljs-built_in">this</span>.xxx = yyy;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p>如果属性和方法是公共的，每个对象的值都是相同的，可以通过原型来添加</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript">类.prototype.属性名 = 值<br></code></pre></div></td></tr></table></figure>

<h2 id="源码"><a href="#源码" class="headerlink" title="源码"></a>源码</h2><figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//定义一个Myclass类</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Myclass</span>(<span class="hljs-params"></span>) </span>&#123;<br><br>&#125;<br><span class="hljs-comment">//实例化</span><br><span class="hljs-keyword">let</span> mc = <span class="hljs-keyword">new</span> Myclass()<br><br><span class="hljs-built_in">console</span>.log(mc.__proto__ === Myclass.prototype);<br><br><span class="hljs-comment">//向原型中添加一个name属性。</span><br>Myclass.prototype.name = <span class="hljs-string">&quot;向原型添加name&quot;</span><br><span class="hljs-built_in">console</span>.log(mc.name);<br><br><span class="hljs-comment">//加给实例一个name属性</span><br>mc.name = <span class="hljs-string">&quot;swk&quot;</span><br><span class="hljs-built_in">console</span>.log(mc.name);<br><br>Myclass.prototype.sayHi = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`hello,this is <span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span>`</span>);<br>&#125;<br><br>mc.sayHi()<br><br><span class="hljs-comment">//d结果</span><br><br><span class="hljs-comment">//true</span><br><span class="hljs-comment">//向原型添加name</span><br><span class="hljs-comment">//swk</span><br><span class="hljs-comment">//hello,this is swk</span><br></code></pre></div></td></tr></table></figure>


            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/gis-yu/categories/JavaScript/">JavaScript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/gis-yu/tags/JavaScript/">JavaScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/gis-yu/2022/03/03/01-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">01 二分查找</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/gis-yu/2021/12/12/%E6%B5%8F%E8%A7%88%E5%99%A8%E4%B8%AD%E7%9A%84JavaScript%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F/">
                        <span class="hidden-mobile">浏览器中的JavaScript能做什么？</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"zQGDUUOQ9QfQCdRUzRjf2EL9-gzGzoHsz","appKey":"HTVcqUu3ul0Gtn1zPLYul6yt","path":"window.location.pathname","placeholder":"留下你的评论吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":true,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/gis-yu/js/events.js" ></script>
<script  src="/gis-yu/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/gis-yu/js/local-search.js" ></script>



  
    <script  src="/gis-yu/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/gis-yu/js/boot.js" ></script>


<!-- hexo injector body_end start -->
<link rel="stylesheet" href="/css/customize.css">
<!-- hexo injector body_end end --></body>
</html>
